import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  GetUnsettledAndUnfinancedPurchaseOrdersName,
  SupplierEnterpriseInfoGetLockedInfo,
  FinancingApprovalQuotaGetAllByPagedAndSort,
  FinancingApprovalQuotaCreate,
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useEcommercePlatform() {
  const route = useRoute()
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const DialogVisible = ref<boolean>(false);
  const lockSelId = ref()//当前锁定的供应商ID
  const projectList = ref([]) //可选的L
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "企业名称",
      prop: "supplyName",
    },
    {
      label: "采购项目",
      prop: "projectAccountsReceivableName",
    },
    {
      label: "应收账款总金额（元）",
      prop: "accountsReceivable",
    },
    {
      label: "信用级别",
      prop: "creditRating",
    },
    {
      label: "额度核定模型",
      prop: "modelName",
    },
    {
      label: "融资利率",
      prop: "financingRate",
    },
    {
      label: "审核结果",
      prop: "status",
      fixed: "right",
      width: 100,
      cellRenderer: ({ row }) => (
        <span>
          {
            row.status == 0 ? "待审核" : row.status == 1 ? '未通过' : "已通过"
          }
        </span>
      )
    },
  ];
  const EntryPlatform = reactive({
    applicationDate: '',
    arcId: [],
    loanMoney: '',
  })
  // 万亿 长度 14

  async function SubtimEntryPlatform() {
    if (EntryPlatform.applicationDate == '') {
      ElMessage.warning('请选择申请日期')
      return
    }
    if (EntryPlatform.arcId.length == 0) {
      ElMessage.warning('请选择应收款项目')
      return
    }
    if (EntryPlatform.loanMoney > 100000000) {
      ElMessage.warning('应收款项目金额应小于10000万')
      return
    }
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      applicationDate: EntryPlatform.applicationDate + ' 00:00:00',
      projectAccountsReceivable: EntryPlatform.arcId.join(';'),
      SEIId: lockSelId.value,
    };
    const res = await FinancingApprovalQuotaCreate(data);
    if (res.success) {
      ElMessage.success('新增额度核定成功！')
      CloseEntryPlatform();
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  }

  function CloseEntryPlatform() {
    EntryPlatform.applicationDate = ''
    EntryPlatform.arcId = []
    EntryPlatform.loanMoney = 0
    DialogVisible.value = false
  }

  async function getList() {
    const res = await FinancingApprovalQuotaGetAllByPagedAndSort({
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      SEIId: sessionStorage.getItem("seiId"),
    });
    if (res.success) {
      res.data.items.forEach((item) => {
        item.projectAccountsReceivableName = item.projectAccountsReceivableName.split(";").join(",").replace(/^,/, "");
      })
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }

  async function changeDate() {
    const data = qs.stringify({
      seIId: lockSelId.value,
      applicationDate: EntryPlatform.applicationDate,
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let response = await GetUnsettledAndUnfinancedPurchaseOrdersName(data)
    if (response.success) {
      projectList.value = response.data
    } else {
      ElMessage.error(response.msg)
    }
  }
  //计算选中的总额
  function countMoney() {
    let sum = 0
    projectList.value.forEach(item => {
      EntryPlatform.arcId.forEach(a => {
        if (a == item.purchaseOrderId) {
          sum += Number(item.contractAmount)
        }
      })
    })
    EntryPlatform.loanMoney = sum
  }
  onMounted(async () => {
    getList()
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const res = await SupplierEnterpriseInfoGetLockedInfo(data);
    if (res.success) {
      lockSelId.value = res.data.seiId
    } else {
      ElMessage.error(res.msg)
    }
  })

  function handleSizeChange() {
    getList()
  }
  function handleCurrentChange() {
    getList()
  }

  return {
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    DialogVisible,
    EntryPlatform,
    projectList,
    CloseEntryPlatform,
    SubtimEntryPlatform,
    countMoney,
    changeDate
  }
}
